/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;

import com.reddys.rad.inventory.db.Product;
import com.reddys.rad.inventory.db.PurchaseOrder;
import com.reddys.rad.inventory.db.PurchaseOrderDetails;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.helper.PurchaseOrderHelper;
import com.reddys.rad.inventory.service.PurchaseOrderService;
import com.reddys.rad.inventory.utils.AutoCompleteList;
import com.reddys.rad.inventory.utils.EntityManagerImpl;
import com.reddys.rad.inventory.utils.Utilities;
import eu.schudt.javafx.controls.calendar.DatePicker;
import inventory.Inventory;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.beans.property.Property;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.persistence.EntityManager;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class PurchaseOrderController implements Initializable {

    EntityManager em = null;
    Stage stage;
    private final ObservableList data =  FXCollections.observableArrayList();
    Logger log = Utilities.getLogger("PurchaseOrderController");
    @FXML
    TableView tableView;
    
    @FXML
    TextField vendor;
    
    @FXML
    TextField purchaseOrderID;
    
    @FXML
    TextField purchaseOrderDate;
    
    @FXML
    TextField contactPerson;
        
    @FXML
    TextField phone;
        
    @FXML
    TextField location;
    
    @FXML
    VBox vbox1;
    
    Popup popup= new Popup();
                    
    @FXML
    AnchorPane datePickerAnchorPane;
    
    DatePicker birthdayDatePicker = new  DatePicker();
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       this.stage = Inventory.stage;
       tableView.setEditable(true);
       purchaseOrderID.setDisable(true);
       loadTableColumns(tableView);
       addEmptyRows();
         birthdayDatePicker = new DatePicker(Locale.ENGLISH);
         birthdayDatePicker.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
         birthdayDatePicker.getCalendarView().todayButtonTextProperty().set("Today");
         birthdayDatePicker.getCalendarView().setShowWeeks(false);
         birthdayDatePicker.getStylesheets().add("/DatePicker.css");
         datePickerAnchorPane.getChildren().add(birthdayDatePicker);
         DatePicker.setHgrow(birthdayDatePicker, Priority.ALWAYS);
         vendor.setOnMouseClicked(new EventHandler() {

          @Override
          public void handle(Event t) {
              System.out.println(t );

              ArrayList<String> tableColumns = new ArrayList();
              tableColumns.add("Vendor ID");
              tableColumns.add("Vendor Name");
              final TableView popupNode  = new TableView();
              createPopupTableView(popupNode,tableColumns);
              List<Vendor> vendorList = PurchaseOrderService.getVendorList();
              ObservableList tableViewData = FXCollections.observableArrayList();
              for(Vendor vendor:vendorList){
                  ObservableList tableColumnData = FXCollections.observableArrayList();
                  tableColumnData.add(vendor.getVendorid());
                  tableColumnData.add(vendor.getVendorname());
                  tableViewData.add(tableColumnData);
              }
              popupNode.setOnMouseClicked(new EventHandler() {

                  @Override
                  public void handle(Event t) {
                       ObservableList product=(ObservableList)popupNode.getSelectionModel().getSelectedItem();
                       vendor.setText((String) product.get(0));
                       Utilities.hidePopup(popup);
                  }


              });
              popupNode.getItems().addAll(tableViewData);
              popup = Utilities.createPopup(popupNode,tableView);
          }
      });   

    }    

    private void loadTableColumns(final TableView tableView) {
        tableView.setEditable(true);
        
        TableColumn purchaseOrderDetailsID = new TableColumn("Purchase Order Detail ID");
        purchaseOrderDetailsID.setVisible(false);
        Utilities.createCellValueFactory(purchaseOrderDetailsID,0);
       TableColumn productCategory = new TableColumn("Product Category");
        productCategory.setMinWidth(200);
        Utilities.createCellValueFactory(productCategory,0);
        Callback<TableColumn, TableCell> cellFactory =
             new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell();
                 }
             };
        productCategory.setCellFactory(new Callback<TableColumn, TableCell>() {
                                 public TableCell call(TableColumn p) {
                     final TableCell tc  = new TableCell();
                     tc.setOnMouseClicked(new EventHandler() {

                        @Override
                        public void handle(Event t) {
                            System.out.println(t );

                            ArrayList<String> tableColumns = new ArrayList();
                            tableColumns.add("Product ID");
                            tableColumns.add("Product Name");
                            final TableView popupNode  = new TableView();
                            createPopupTableView(popupNode,tableColumns);
                            List<Product> productList = PurchaseOrderService.getProducts();
                            ObservableList tableViewData = FXCollections.observableArrayList();
                            for(Product product:productList){
                                ObservableList tableColumnData = FXCollections.observableArrayList();
                                tableColumnData.add(product.getProductId());
                                tableColumnData.add(product.getProductDescription());
                                tableViewData.add(tableColumnData);
                            }
                            popupNode.setOnMouseClicked(new EventHandler() {

                                @Override
                                public void handle(Event t) {
                                     ObservableList product=(ObservableList)popupNode.getSelectionModel().getSelectedItem();
                                     tc.setText((String) product.get(0));
                                     Utilities.hidePopup(popup);
                                }


                            });
                            popupNode.getItems().addAll(tableViewData);
                            popup = Utilities.createPopup(popupNode,tableView);
                        }
                    });   
                    
                    return tc;

             }
        });
        final TableColumn productID = new TableColumn("Product ID");
        productID.setMinWidth(100);
       
        Utilities.createCellValueFactory(productID,1);

        productID.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                     final TableCell tc  = new TableCell();
                     tc.setOnMouseClicked(new EventHandler() {

                        @Override
                        public void handle(Event t) {
                            System.out.println(t );

                            ArrayList<String> tableColumns = new ArrayList();
                            tableColumns.add("Product ID");
                            tableColumns.add("Product Name");
                            final TableView popupNode  = new TableView();
                            createPopupTableView(popupNode,tableColumns);
                            List<Product> productList = PurchaseOrderService.getProducts();
                            ObservableList tableViewData = FXCollections.observableArrayList();
                            for(Product product:productList){
                                ObservableList tableColumnData = FXCollections.observableArrayList();
                                tableColumnData.add(product.getProductId());
                                tableColumnData.add(product.getProductDescription());
                                tableViewData.add(tableColumnData);
                            }
                            popupNode.setOnMouseClicked(new EventHandler() {

                                @Override
                                public void handle(Event t) {
                                     ObservableList product=(ObservableList)popupNode.getSelectionModel().getSelectedItem();
                                     tc.setText((String) product.get(0));
                                     Utilities.hidePopup(popup);
                                }


                            });
                            popupNode.getItems().addAll(tableViewData);
                            popup = Utilities.createPopup(popupNode,tableView);
                        }
                    });   
                    
                    return tc;
                 }
             });
         TableColumn productName = new TableColumn("Product Name");
        productName.setMinWidth(300);
        Utilities.createCellValueFactory(productName,2);
        
         
        TableColumn itemCode = new TableColumn("Item Code");
        itemCode.setMinWidth(100);
        Utilities.createCellValueFactory(itemCode,3);
      
 
        TableColumn quantity = new TableColumn("Quantity");
        quantity.setMinWidth(200);
        Utilities.createCellValueFactory(quantity,4);
        quantity.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Quantity");
                 }
             });
               
        TableColumn uom = new TableColumn("Uom");
        uom.setMinWidth(200);
        Utilities.createCellValueFactory(uom,7);
        uom.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UOM");
                 }
             });
        
        TableColumn unitPrice = new TableColumn("Unit Price");
        unitPrice.setMinWidth(100);
        Utilities.createCellValueFactory(unitPrice,8);
        unitPrice.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UnitPrice");
                 }
             });
 
        TableColumn qtyReceived = new TableColumn("Quantity Received");
        qtyReceived.setMinWidth(200);
        qtyReceived.setVisible(false);
        Utilities.createCellValueFactory(qtyReceived,5);
        qtyReceived.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Discount");
                 }
             });
        
        TableColumn balanceQty = new TableColumn("balance qty");
        balanceQty.setMinWidth(200);
        balanceQty.setVisible(false);
        Utilities.createCellValueFactory(balanceQty,6);
        balanceQty.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("SubTotal");
                 }
             });
        tableView.getColumns().addAll(productCategory, productID, productName,itemCode, quantity,qtyReceived, balanceQty,uom,unitPrice,purchaseOrderDetailsID);
        System.out.println("dat123232-----"+data);
        tableView.getItems().setAll(data);
 
    }
    
    @FXML
    private void addEmptyRows() {
       System.out.println("add Rows");
        for(int i=0;i<10;i++){
            ObservableList purchaseOrderDetailsList = FXCollections.observableArrayList();
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
             purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
            purchaseOrderDetailsList.add("");
             data.add(purchaseOrderDetailsList);
        }
        tableView.getItems().setAll(data);
      }
    
    @FXML
    private void clearRows() {
        tableView.getItems().clear();
    }
    
    private void createPopupTableView(TableView popupNode, ArrayList<String> tableColumns) {
                double tcWidth = popupNode.getWidth()/tableColumns.size();
                ObservableList tableColumnsData = FXCollections.observableArrayList();
               for(int i=0;i<tableColumns.size();i++){
                   TableColumn tc = new TableColumn(tableColumns.get(i));
                   Utilities.createCellValueFactory(tc, i);
                   tc.setMinWidth(100);
                   tableColumnsData.add(tc);
               }
               popupNode.getColumns().addAll(tableColumnsData);
   }

    @FXML
    private void save() {
        try{
        if(validateSave()){
        em = EntityManagerImpl.getEntityManager();
            EntityManagerImpl.beginTransaction(em);
        PurchaseOrder  purchaseOrder = new PurchaseOrder();
        purchaseOrder.setPurchaseOrderDate(birthdayDatePicker.getSelectedDate());
        String vendorId =  vendor.getText();
        purchaseOrder.setVendorId(vendorId);
        purchaseOrder.setStatus(location.getText());
        purchaseOrder = getPurchaseOrderService().saveHeader(purchaseOrder,em);
       
        ArrayList purchaseOrderDetails = PurchaseOrderHelper.getPurchaseOrderDetails(tableView,purchaseOrder);
        for(int i=0;i<purchaseOrderDetails.size();i++){
            PurchaseOrderDetails details = (PurchaseOrderDetails) purchaseOrderDetails.get(i);
            getPurchaseOrderService().save(details, em);
        }
        purchaseOrderID.setText(purchaseOrder.getPurchaseOrderId());
    
       }
       EntityManagerImpl.commitTransaction(em);
       Utilities.createDialog("Transaction Completed Successfully");
    
    }catch(Exception e){
        e.printStackTrace();
        log.info(e.getMessage());
        EntityManagerImpl.rollbackTransaction(em);
        Utilities.createDialog("Transaction Failed");
    }
    }
    public PurchaseOrderService getPurchaseOrderService(){
        PurchaseOrderService purchaseOrderService = new PurchaseOrderService();
        return purchaseOrderService;
    }

    private boolean validateSave() {
        boolean purchaseDetailsBoolean = true;
        if(null == birthdayDatePicker.getSelectedDate()){
            Utilities.createDialog("Please Select Purchase Order Date");
            return false;
        }
        
         
        if(Utilities.isNull(vendor.getText())){
            Utilities.createDialog("Please Select Vendor");
            return false;
        }
      
        for(int i =0;i<tableView.getItems().size();i++){
        ObservableList purchaseOrderDetails = (ObservableList) tableView.getItems().get(i);
        if(purchaseOrderDetails.get(1)!=null && purchaseOrderDetails.get(1).toString().isEmpty()){
            purchaseDetailsBoolean = false;
            if(null ==purchaseOrderDetails.get(8)) {
                Utilities.createDialog("Please enter Quantity");
                return false;
            }
            if(null == purchaseOrderDetails.get(7) && purchaseOrderDetails.get(7).toString().isEmpty()) {
                Utilities.createDialog("Please enter Uom");
                return false;
            }
        }
        }
        if(purchaseDetailsBoolean){
             Utilities.createDialog("Please Add Atleast one Product");
            return false;
        }
        return true;
    }
    


  public class EditingCell extends TableCell<Object, String> {
        private String columnName ;
        private TextField textField;
        TableCell tableCell;
 ObservableList purchaseOrderDetails = FXCollections.observableArrayList();
        public EditingCell() {
            this.tableCell = this;
        }
       public EditingCell(String columnName ) {
           this.columnName = columnName;
           this.tableCell = this;
        }
 
        @Override
        public void startEdit() {
           
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();

        }
 
        @Override
        public void cancelEdit() {
            super.cancelEdit();
 
            setText((String) getItem());
            setGraphic(null);
        }
 
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
 
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }
    public Property<String> inputText()
    {
        return textField.textProperty();
    }

        private void createTextField() {
            purchaseOrderDetails = (ObservableList) (this.getTableRow().getItem());
             
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
   
            textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
                @Override
                public void changed(ObservableValue<? extends Boolean> arg0, 
                    Boolean arg1, Boolean arg2) {
                        if (!arg2) {
                             commitEdit(textField.getText());
                        System.out.println("Focus out");
                     System.out.println("createtext"+textField.getText());
                     if(columnName.equalsIgnoreCase("Quantity")){
                        if(textField.getText() !=null)
                         purchaseOrderDetails.set(4,Utilities.isNull(textField.getText())?"0.0":textField.getText());
                        purchaseOrderDetails.set(5,Utilities.isNull(textField.getText())?"0.0":textField.getText());
                    }else if(columnName.equalsIgnoreCase("UOM")){
                        purchaseOrderDetails.set(7,textField.getText());
                    }else if(columnName.equalsIgnoreCase("UnitPrice")){
                       purchaseOrderDetails.set(8,textField.getText());
                    }else if(columnName.equalsIgnoreCase("Discount")){
                         if(textField.getText() !=null)
                        purchaseOrderDetails.set(5,Utilities.isNull(textField.getText())?"0.0":textField.getText());
                    }else if(columnName.equalsIgnoreCase("SubTotal")){
                        if(textField.getText() !=null)
                        purchaseOrderDetails.set(6,Utilities.isNull(textField.getText())?"0.0":textField.getText());
                    }else if(columnName.equalsIgnoreCase("ProductCategory")){
                         purchaseOrderDetails.set(0,textField.getText());
                    }else if(columnName.equalsIgnoreCase("ProductID")){
                        final ObservableList purchaseOrderDetailsCell = FXCollections.observableArrayList();
                         purchaseOrderDetailsCell.add(purchaseOrderDetails.get(0));
                         purchaseOrderDetailsCell.add(textField.getText());
                         purchaseOrderDetailsCell.add(purchaseOrderDetails.get(2));
                         purchaseOrderDetailsCell.add(purchaseOrderDetails.get(3));
                         purchaseOrderDetailsCell.add(purchaseOrderDetails.get(4));
                        purchaseOrderDetailsCell.add(purchaseOrderDetails.get(5));
                         purchaseOrderDetailsCell.add(purchaseOrderDetails.get(6));
                        purchaseOrderDetailsCell.add(purchaseOrderDetails.get(7));
                        purchaseOrderDetailsCell.add(purchaseOrderDetails.get(8));
                        purchaseOrderDetailsCell.add(purchaseOrderDetails.get(9));
           

                          tableCell.getTableView().getItems().set(tableCell.getTableRow().getIndex(), purchaseOrderDetailsCell);
                          System.out.println("tableCell---->"+tableCell.getTableView().getItems().get(tableCell.getTableRow().getIndex()));
                         }
                        }

                       }

                       
            });
        }
 
        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
        
  }
  
}
